package com.common.auth;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

/**
 * 内存存储用户认证信息
 * @author guanghong.ji
 * @date   2018年6月8日
 */
public class MemoryAuthenRepository implements MyAuthenRepository {

	private volatile Long tokenExpireTimeLong = 86400L;
	private volatile HashMap<String, MyAuthenticationInfo> authenMap = new HashMap<String, MyAuthenticationInfo>();
	
	private MemoryAuthenRepository() {}
	
	private static volatile MemoryAuthenRepository instance;
	public static MemoryAuthenRepository getInstance() {
		if(instance == null) instance = new MemoryAuthenRepository();
		return instance;
	}
	@Override
	public MyAuthenticationInfo saveAuthenInfo(MyAuthenticationInfo info) {
		if(info == null || StringUtils.isBlank(info.getToken()) || info.getUserId() == null) return null;
		MyAuthenticationInfo oldAuthen = getAuthenByUserId(info.getUserId());
		if(oldAuthen != null) {
			oldAuthen.freshTokenExpireTime(tokenExpireTimeLong);
			return oldAuthen;
		}
		else {
			authenMap.put(info.getToken(), info);
			return info;
		}
	}

	@Override
	public boolean freshToken(String token) {
	  if(StringUtils.isBlank(token) || !authenMap.containsKey(token)) return false;
	  
	  MyAuthenticationInfo info = authenMap.get(token);
	  info.freshTokenExpireTime(tokenExpireTimeLong);
	  
	  authenMap.put(token, info);
	  
	  return true;
	}

	@Override
	public boolean removeAuthenInfo(String token) {
		if(StringUtils.isBlank(token) || !authenMap.containsKey(token)) return false;
		
		authenMap.remove(token);
		
		return true;
	}
	@Override
	public void setTokenExpireTimeLong(Long timeLong) {
		if(timeLong != null && timeLong > 0) tokenExpireTimeLong = timeLong;
	}
	@Override
	public MyAuthenticationInfo getAuthenByToken(String token) {
		if(StringUtils.isBlank(token)) return null;
		return authenMap.get(token);
	}
	@Override
	public MyAuthenticationInfo getAuthenByUserId(Integer userId) {
		if(userId == null) return null;
		Iterator<Entry<String, MyAuthenticationInfo>> iterator = authenMap.entrySet().iterator();
		while(iterator.hasNext()) {
			MyAuthenticationInfo authen = iterator.next().getValue();
			if(userId.equals(authen.getUserId())) return authen;
		}
		return null;
	}

}
